import { Modal } from "antd";
import { useImperativeHandle, useState } from "react";
import api from "../../../../api";
import { message } from "../../../../utils/AntdGlobal";
import type { Order } from "../../../../types/api";

export default function OrderRoute(props: any) {
    const [visible, setVisible] = useState(false)
    const [trackAni, setTrackAni] = useState<{
        cancel: () => void
    }>()

    useImperativeHandle(props.ref, () => {
        return {
            open
        }
    })

    const open = async (orderId: string) => {
        const detail = await api.getOrderDetail(orderId)
        if (detail.route.length) {
            setVisible(true)
            setTimeout(() => {
                renderMap(detail)
            }, 100)
        } else {
            message.info('请先完成打点上报')
        }
    }

    const renderMap = (detail: Order.OrderItem) => {
        const map = new window.BMapGL.Map('routeMap')
        map.enableScrollWheelZoom()
        map.centerAndZoom(detail.cityName, 17)

        const path = detail.route || []
        const point = []
        for (let i = 0; i < path.length; i++) {
            point.push(new window.BMapGL.Point(path[i].lng, path[i].lat))
        }
        const polyline = new window.BMapGL.Polyline(point, {
            strokeWeight: '8',
            strokeOpacity: 0.8,
            strokeColor: '#ed6c00'
        })

        setTimeout(start, 1000)
        function start() {
            const trackAni = new window.BMapGLLib.TrackAnimation(map, polyline, {
                overallView: true,
                tilt: 30,
                duration: 20000,
                delay: 300
            });
            trackAni.start()
            setTrackAni(trackAni)
        }
    }

    const handleCancel = () => {
        setVisible(false)
        trackAni?.cancel()
    }
    return (
        <Modal
            title='路线轨迹'
            width={1100}
            open={visible}
            footer={false}
            onCancel={handleCancel}>
            <div id="routeMap" style={{ height: 450 }}></div>
        </Modal>
    )
}